package com.yy.ant.sys.controller;


import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yy.ant.sys.entity.RoleResources;
import com.yy.ant.sys.entity.UserRole;
import com.yy.ant.sys.service.IRoleResourcesService;
import com.yy.model.ResultMsg;
import com.yy.model.enums.ResultEnum;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liyingying
 * @since 2019-12-20
 */
@RestController
@RequestMapping("/sys/role-resources")
public class RoleResourcesController {
	
	@Autowired
	private IRoleResourcesService iRoleResourcesService;
	
	/**
	 *授权列表
	 * @return
	 */
	@RequestMapping(value = "/roleResources")
	public ResultMsg roleResources(@RequestParam(value = "roleid")String roleid,@RequestParam(value = "resourcesid")String resourcesid) {
		
		List<RoleResources> list=new ArrayList<RoleResources>();
		List<String> list2=new ArrayList<String>();
		String[] id = roleid.split(",");
		String[] rid = resourcesid.split(",");
        for (int i = 0; i < id.length; i++) {
        	if (StringUtils.isNotEmpty(id[i])) {
        		for (int j = 0; j < rid.length; j++) {
        			if (StringUtils.isNotEmpty(rid[j])) {
        				 list2.add(id[i]); 
        				 RoleResources roleResources=new RoleResources();
        				 roleResources.setResourcesId(Long.valueOf(rid[j]));
        				 roleResources.setRoleId(Long.valueOf(id[i]));
        				 list.add(roleResources);
        			}
        		}
			}
        }
        //先删除
        iRoleResourcesService.remove(new QueryWrapper<RoleResources>().in("role_id", list2));
        //批量新增
        boolean b= iRoleResourcesService.saveBatch(list);
		ResultMsg resultMsg=new ResultMsg();
        if (b) {
        	resultMsg.setSuccess(true);
			resultMsg.setMsg(ResultEnum.sucess_grant_failed.getMsg());
		}else {
			resultMsg.setMsg(ResultEnum.error_grant_upload.getMsg());
		}
		return resultMsg;
	}
	
	/**
	 * 根据角色ID查询菜单ID
	 * @param roleid
	 * @return
	 */
	@RequestMapping(value = "/rResourcesList")
	public ResultMsg rResourcesList(@RequestParam(value = "roleid")String roleid) {
		//根据用户ID找到菜单ID
		 List<Long> longs=new ArrayList<>();
		List<RoleResources> list1=iRoleResourcesService.list(new QueryWrapper<RoleResources>().eq("role_id", roleid));
		for (RoleResources o:list1) {
			longs.add(o.getResourcesId());
		}
		ResultMsg resultMsg=new ResultMsg();
		resultMsg.setData(longs);
		return resultMsg;
	}
}
